# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.api import users
import ytblog.model.blog
from ytblog.model.tag import TagInfo
import ytblog.model.authorization as authorization
import ytblog.config

#tag check decorator
def check_tag(method):
  def new_method(self, *args, **kwds):
    if ytblog.config.FREE_TAGS:
      method(self, *args, **kwds)
      return
    
    if ytblog.config.MIN_TAG_NUM > 0 and not self.request.get('tags'):
      self.error(404)
      return      
  
    tags = self.request.get('tags').split('/')[0:ytblog.config.MAX_TAG_NUM]
    
    for tag in tags:
      if not TagInfo.get_by_name(tag): #the tag must already exist
        self.error(404)
        return
    
    method(self, *args, **kwds)
            
  return new_method

#decorator
def check_blog_id(method):
  def new_method(self, *args, **kwds):
    if not len(args) > 0:
      self.error(404)
      return
        
    #the first parameter should be blog id
    if ytblog.model.blog.Blog.get_by_str_id(args[0]) is None:
      self.error(404)
      return
    
    method(self, *args, **kwds)
            
  return new_method

#check id decorator
def check_id(cls):
  def decorator(method):  
    def new_method(self, *args, **kwds):
      if not len(args) > 0:
        self.error(404)
        return
        
      #the first parameter should be object id
      if cls.get_by_str_id(args[0]) is None:
        self.error(404)
        return
    
      method(self, *args, **kwds)
            
    return new_method
  return decorator

#authorization decorator
def authorize(cls, operation):
  def decorator(method):
    def new_method(self, *args, **kwds):
      obj = None
      if len(args) > 0 and operation != authorization.OPERATION_ADD:
        #the first parameter should be object id
        obj = cls.get_by_str_id(args[0])
            
      auth = authorization.get_auth((cls, obj))
      if auth.has_key(operation):
        auth_result = auth[operation]
      else:
        auth_result = False
        
      if auth_result == False:
        self.error(404)
        return
    
      method(self, *args, **kwds)
            
    return new_method
  return decorator
